package com.powerunion.datacollection.dao.impl;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.Format;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.ViewDataDao;
import com.powerunion.datacollection.model.ActivityInfo;
import com.powerunion.datacollection.model.jsonObject.TaskInfo;
import com.powerunion.datacollection.persistence.db.jdbc.operator.QueryOperator;
import com.powerunion.datacollection.persistence.db.jdbc.operator.RsDataSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameter;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlType;
import com.powerunion.util.DBUtils;
import com.powerunion.util.log.LogHelper;

public class ViewDataDaoImpl extends JdbcBase implements ViewDataDao {
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			ViewDataDaoImpl.class);

	public List getViewDataByUser(String userCode) throws DaoException {

		StringBuffer sql = new StringBuffer();

		sql
				.append(
						"select s.id,s.proc_id,t.item_name,w.wf_instance_desc,w.wf_name,s.act_id,")
				.append("s.staff_id,s.approve_mind_date,s.aw_state, s.form_id,s.create_date,(select act_name from dc_proc_instance ")
				.append(
						"where id =s.pre_act_id )preActName  from dc_item_info t left join dc_approve_work s on s.proc_id = t.id ")
				.append(
						" left join dc_wf_instance w on t.id = w.proc_id   ")
				.append(
						" where s.act_id = ? and aw_state <> 0  and  aw_state <> 1 and aw_state <> 2 and  aw_state <> 3 ")
				.append(
						"and  aw_state <> 6   and s.aw_state <> 7  and s.aw_state <> 8 and s.aw_state <> 9 ");

		Connection conn = null;
		List worksIds = null;
		List viewDataWorks = null;
		try {
			conn = this.getConnection();
			worksIds = this.findAllCompleteApproveWorkByUser(userCode, conn);
			viewDataWorks = new ArrayList();

			for (Iterator iter = worksIds.iterator(); iter.hasNext();) {
				String workId = (String) iter.next();
				QueryOperator query = new QueryOperator();
				query.setPresentConnection(conn);
				query.setSql(sql.toString());
				query.setUseOnlyConnectionFlag(true);

				query.addParameter(new SqlParameter(SqlType.VARCHAR, workId));

				query.access();

				if (query.resultSetAvailable()) {// 检查结果集是否可用
					// 获取并处理记录集
					RsDataSet rs = new RsDataSet(query.getSqlResultSet());
					for (int i = 0; i < rs.rowCount; i++) {
						TaskInfo swi = new TaskInfo();
						swi.setId(rs.getFieldValueAsString("id"));
						swi.setProcId(rs.getFieldValueAsString("proc_id"));
						swi.setProcName(rs.getFieldValueAsString("item_name"));
						swi.setTaskDesc(rs
								.getFieldValueAsString("wf_instance_desc"));
						swi.setTaskName(rs.getFieldValueAsString("wf_name"));
						swi.setActId(rs.getFieldValueAsString("act_id"));
						swi.setType(Constants.TASK_TYPE_APPROVEWORK);
						swi.setStaffId(rs.getFieldValueAsString("staff_id"));
						Date upDate = rs.getFieldValueAsDate("approve_mind_date");
						if(upDate != null){
							String upDateStr = Format.getInstance().dateToString(
									upDate);
							swi.setUpDateStr(upDateStr);
						}else{
							swi.setUpDateStr("");
						}
						
						Date createDate = rs.getFieldValueAsDate("create_date");
						if(createDate != null){
							String createDateStr = Format.getInstance().dateToString(
									createDate);
							swi.setCreateDate(createDateStr);
						}else{
							swi.setCreateDate("");
						}

						swi.setFormId(rs.getFieldValueAsString("form_id"));
						swi.setState(rs.getFieldValueAsInteger("aw_state")
								.intValue());
						swi.setPreActName(rs.getFieldValueAsString("preActName"));

						viewDataWorks.add(swi);

						rs.next();
					}
					rs.clearAll();
				}
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("");
		} finally {
			DBUtils.close(conn);
		}
		return viewDataWorks;
	}
	
	

	private List findAllCompleteApproveWorkByUser(String userCode,
			Connection conn) throws DaoException {
		List activities = null;
		List approveWorkList = null;
		try {
			conn = this.getConnection();
			activities = this.findAllCompleteApproveWork();
			approveWorkList = new ArrayList();

			for (Iterator iter = activities.iterator(); iter.hasNext();) {
				ActivityInfo activityInfo = (ActivityInfo) iter.next();
				String[] types = StringUtils.split(activityInfo
						.getExamineUserOrcollectionUserTypes(), ",");
				String[] codes = StringUtils.split(activityInfo
						.getExamineUserOrcollectionUser(), ",");
				if (types != null && types.length == codes.length) {
					for (int i = 0; i < codes.length; i++) {
						String code = codes[i];
						String type = types[i];
						if (!StringUtils.isEmpty(type)) {
							if (type.equals("user")) {
								if (userCode.equals(code)) {
									approveWorkList.add(activityInfo
											.getActivityId());
									break;
								}
							} else if (type.equals("group")) {
								boolean flag = this.iUsercodeInWorkGroup(userCode,
										code, conn);
								if (flag) {
									approveWorkList.add(activityInfo
											.getActivityId());
									break;
								}
							} else if (type.equals("department")) {
								boolean flag = this.iUsercodeInDept(userCode, code,
										conn);
								if (flag) {
									approveWorkList.add(activityInfo
											.getActivityId());
									break;
								}
							}
						}

					}
				}
				

			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("");
		}

		return approveWorkList;
	}

	private List findAllCompleteApproveWork() throws DaoException {
		StringBuffer sql = new StringBuffer();

		sql
				.append(
						"select id, examRol_Or_colRol,exa_Or_col_type,act_name from dc_proc_instance where ")
				.append(
						"id in (select act_id from dc_approve_work where aw_state =5) and act_type = '1' ");

		List activities = null;

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());

		try {
			activities = new ArrayList();
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					ActivityInfo activityInfo = new ActivityInfo();
					activityInfo.setActivityId(rs.getFieldValueAsString("id"));
					activityInfo.setExamineUserOrcollectionUser(rs
							.getFieldValueAsString("examRol_Or_colRol"));
					activityInfo.setExamineUserOrcollectionUserTypes(rs
							.getFieldValueAsString("exa_Or_col_type"));
					activityInfo.setActivityName(rs
							.getFieldValueAsString("act_name"));

					activities.add(activityInfo);

					rs.next();
				}

				rs.clearAll();
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("根据已办审批任务查找相应的流程环节失败！");
		}

		return activities;
	}

	/**
	 * 判断该角色下部门类型中的部门是否存在该用户
	 * 
	 * @param userCode
	 * @param roleId
	 * @param conn
	 * @return
	 * @throws DaoException
	 */
	private boolean iUsercodeInDept(String userCode, String code,
			Connection conn) throws DaoException {
		// 得到该角色下的部门类型的id

		StringBuffer sql = new StringBuffer();
		sql.append("select user_code from user_dept where fram_seq = ? ")
				.append(" and user_code = ?");

		boolean flag = false;

		try {
			QueryOperator query = new QueryOperator();
			query.setSql(sql.toString());
			query.setUseOnlyConnectionFlag(true);
			query.setPresentConnection(conn);
			query.addParameter(new SqlParameter(SqlType.VARCHAR, code));
			query.addParameter(new SqlParameter(SqlType.VARCHAR, userCode));

			query.access();
			if (query.resultSetAvailable()) {// 检查结果集是否可用
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					flag = true;
				}
				rs.clearAll();
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("");
		}
		return flag;

	}

	private boolean iUsercodeInWorkGroup(String userCode, String code,
			Connection conn) throws DaoException {

		StringBuffer sql = new StringBuffer();
		sql.append("select user_code from user_group where grop_code = ? ")
				.append(" and user_code = ?");

		boolean flag = false;

		try {

			QueryOperator query = new QueryOperator();
			query.setSql(sql.toString());
			query.setUseOnlyConnectionFlag(true);
			query.setPresentConnection(conn);
			query.addParameter(new SqlParameter(SqlType.VARCHAR, code));
			query.addParameter(new SqlParameter(SqlType.VARCHAR, userCode));

			query.access();
			if (query.resultSetAvailable()) {// 检查结果集是否可用
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					flag = true;
				}
				rs.clearAll();
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("");
		}
		return flag;
	}

	/**
	 * 查找有浏览权限的用户可查看的任务
	 * 
	 * @param userCode
	 *            用户编码
	 * @return
	 * @throws DaoException
	 */
	public List findCompleteApproveWorkByViewUser(String userCode)
			throws DaoException {
		StringBuffer sql = new StringBuffer();

		sql
				.append(
						"select s.id,s.proc_id,t.item_name,w.wf_instance_desc,w.wf_name,s.act_id,")
				.append("s.staff_id,s.date_approve,s.aw_state, ")
				.append(
						" s.form_id from dc_item_info t left join dc_approve_work s on s.proc_id = t.id ")
				.append(
						" left join dc_wf_instance w on t.id = w.proc_id  where s.staff_id = ? ")
				.append(
						" and aw_state <> 0  and  aw_state <> 1 and  aw_state <> 3 and  aw_state <> 6 ")
				.append(
						"  and s.aw_state <> 7  and s.aw_state <> 8 and s.aw_state <> 9 ");

		List approveWorkList = null;

		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, userCode));

		try {
			approveWorkList = new ArrayList();
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					// SubmissionWorkItem swi = new SubmissionWorkItem();
					TaskInfo swi = new TaskInfo();
					swi.setId(rs.getFieldValueAsString("id"));
					swi.setProcId(rs.getFieldValueAsString("proc_id"));
					swi.setProcName(rs.getFieldValueAsString("item_name"));
					swi.setTaskDesc(rs
							.getFieldValueAsString("wf_instance_desc"));
					swi.setTaskName(rs.getFieldValueAsString("wf_name"));
					swi.setActId(rs.getFieldValueAsString("act_id"));
					swi.setType(Constants.TASK_TYPE_APPROVEWORK);
					swi.setStaffId(rs.getFieldValueAsString("staff_id"));
//					Date upDate = rs.getFieldValueAsDate("date_approve");
//					String upDateStr = Format.getInstance().dateToYMD(upDate);
//					swi.setUpDateStr(upDateStr);
					swi.setUpDateStr(rs.getFieldValueAsString("date_approve"));
					swi.setFormId(rs.getFieldValueAsString("form_id"));
					swi.setState(rs.getFieldValueAsInteger("aw_state")
							.intValue());

					approveWorkList.add(swi);

					rs.next();
				}

				rs.clearAll();
			}

		} catch (Exception e) {
			logger.error("查找用户编码为：" + userCode + "的已办采集任务失败！", e);
			throw new DaoException("查找用户编码为：" + userCode + "的已办采集任务失败！");
		}

		return approveWorkList;
	}

}
